﻿using System;
using System.Web;

namespace GetExceptional
{
  public class GetExceptionalModule : IHttpModule
  {
    /// <summary>
    /// You will need to configure this module in the web.config file of your
    /// web and register it with IIS before being able to use it. For more information
    /// see the following link: http://go.microsoft.com/?linkid=8101007
    /// </summary>
    #region IHttpModule Members

    public void Dispose()
    {
      //clean-up code here.
    }

    public void Init(HttpApplication context)
    {
      context.Error += new EventHandler(OnError);
    }

    #endregion

    public void OnError(Object source, EventArgs e)
    {
      HttpContext ctx = HttpContext.Current;
      HttpRequest request = ctx.Request;
      Exception exception = ctx.Server.GetLastError();

      //the one we ultimately want to report may be inner to an httpunhandled exception
      if (exception.InnerException != null) exception = exception.InnerException;

      //report a 404 if found
      if (exception is HttpException && ((HttpException)exception).GetHttpCode() == 404)
      {
        Exceptional.ReportNotFound(request);
      }
      else
      {
        Exceptional.ReportException(exception, request, ctx.Session);
      }
    }
  }
}
